<?php

namespace app\api\controller;

use app\api\server\User as ServerUser;
use app\common\controller\Api;
use app\common\model\goods\category\Group as CategoryGroup;
use app\common\model\MoneyLog;
use app\common\model\order\Goods;
use app\common\model\order\Order;
use app\common\model\User;
use app\common\model\user\Group;
use app\common\model\user\Info;
use app\common\model\UserGroup;
use think\Db;

/**
 * 定时任务
 */
class Crontab extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    //  MoneyLog::commission($order);
    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (结算分佣)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function settlement_commission()
    {

        Db::startTrans();
        try {
            $orders = Order::all(['order_status' => '30', 'is_settle' => '0']);
            if ($orders) {
                MoneyLog::commission($orders);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }
    /**
     * @Author LK
     * @date: 2024-01-03 
     * @ApiTitle (平级（日结）)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function parallel_award()
    {
        $users = User::all(['group_id' => ['>', 2]]);
        if (!$users) {
            return 'success';
        }
        try {
            foreach ($users as $k => $v) {
                $uids = ServerUser::diguis($v['id'], $v['group_id']);
                foreach ($uids as $kk => $vv) {
                    $ids = User::where("find_in_set({$vv},paren_ids)")->column('id');
                    array_push($ids, $vv);
                    $total_fee = Order::whereIn('user_id', $ids)->where('is_settle', '1')->whereTime('settletime', 'yesterday')->sum('performance');
                    $parallel = 0;
                    if (in_array($v['group_id'], [3, 4])) {
                        $group = UserGroup::get($v['group_id']);
                        if ($group->parallel_grade > 0) {
                            $parallel_grade = $group->parallel_grade / 100;
                            $parallel = bcmul($total_fee, $parallel_grade, 2);
                        }
                    }
                    if ($parallel > 0) {
                        User::money($parallel, $v['id'], '平级奖（日结）');
                    }
                }
            }
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
        return 'success';
    }
    /**
     * @Author LK
     * @date: 2024-01-03 
     * @ApiTitle (销售奖（月结）)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function sales_prize()
    {
        $users = User::all(['group_id' => ['>', 2]]);
        if (!$users) {
            return 'success';
        }
        try {
            foreach ($users as $k => $v) {
                $uids = ServerUser::diguis($v['id'], $v['group_id']);
                $total_fee = $total_num = 0;
                foreach ($uids as $kk => $vv) {
                    $ids = User::where("find_in_set({$vv},paren_ids)")->column('id');
                    array_push($ids, $vv);
                    $total_num += Order::whereIn('user_id', $ids)->where('is_settle', '1')->whereTime('settletime', 'last month')->sum('total_num');
                    $total_fee += Order::whereIn('user_id', $ids)->where('is_settle', '1')->whereTime('settletime', 'last month')->sum('performance');
                }
                $group = UserGroup::get($v['group_id']);
                if ($total_num >= $group['sales_award_salse_month'] && $total_fee >= $group['sales_award_money_month']) {
                    if ($group->sales_award_month > 0) {
                        $sales_award_month = $group->sales_award_month / 100;
                        $sales_award = bcmul($total_fee, $sales_award_month, 2);
                        User::money($sales_award, $v['id'], '销售奖（月结）');
                    }
                }
            }
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
        return 'success';
    }
    /**
     * @Author LK
     * @date: 2024-01-03 
     * @ApiTitle (销售奖（年结）)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function sales_prize_year()
    {
        $users = User::all(['group_id' => 5]);
        if (!$users) {
            return 'success';
        }
        try {
            $group = UserGroup::get(5);
            foreach ($users as $k => $v) {
                $uids = ServerUser::diguis($v['id'], $v['group_id']);
                foreach ($uids as $kk => $vv) {
                    $ids = User::where("find_in_set({$vv},paren_ids)")->column('id');
                    array_push($ids, $vv);
                    $total_num = Order::whereIn('user_id', $ids)->where('is_settle', '1')->whereTime('settletime', 'last year')->sum('total_num');
                    if ($total_num >= $group['sales_award_salse_year'] && $group['sales_award_year'] > 0) {
                        User::money($group['sales_award_year'], $v['id'], '销售奖（年结）');
                    }
                }
            }
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
        return 'success';

    }

    /**
     * @Author LK
     * @date: 2024-01-03 
     * @ApiTitle (团队奖（月结）)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function Team_prize_month()
    {
        $users = User::all(['group_id' => 5]);
        if (!$users) {
            return 'success';
        }
        try {
            $group = UserGroup::get(5);
            foreach ($users as $k => $v) {
                $uids = ServerUser::diguis($v['id'], 5);
                $total_fee = 0;
                foreach ($uids as $kk => $vv) {
                    $ids = User::where("find_in_set({$vv},paren_ids)")->column('id');
                    array_push($ids, $vv);
                    $total_fee += Order::whereIn('user_id', $ids)->where('is_settle', '1')->whereTime('settletime', 'last month')->sum('performance');
                }
                if ($total_fee > 0 && $group->team_award_month > 0) {
                    $team_award_month = $group->team_award_month / 100;
                    $money = bcmul($total_fee, $team_award_month, 2);
                    User::money($money, $v['id'], '团队奖（月结）');
                }
            }
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
        return 'success';

    }

    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (自动收货)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function auto_take()
    {
        Db::startTrans();
        try {
            $order = Order::all(['order_status' => '20']);
            $auto_take_day = config('site.auto_take_day');
            if ($auto_take_day > 0) {
                $take_time = bcmul($auto_take_day, 86400, 0);
            } else {
                $take_time = 0;
            }
            $time = time();
            if ($order) {
                foreach ($order as $k => $v) {
                    if ($take_time > 0 && $v->sendtime + $take_time > $time) {
                        continue;
                    }
                    $v->taketime = time();
                    $v->order_status = '30';
                    $v->save();
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return 'success';
    }
}
